<template>
  <section>
    <!--高级工具条开始-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="loadListDatagaoji">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--高级查询结束-->

    <!--列表开始-->
    <el-table :data="listData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" :formatter="formatSex" >
      </el-table-column>
      <el-table-column prop="parts.name" label="上级部门" width="120" >
      </el-table-column>
      <el-table-column prop="employee.username" label="负责人" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--列表结束-->

    <!--新增界面开始-->
    <!--
      label：要展示给用户看的数据
    -->
    <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="editForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="负责人" >
          <!--<el-input v-model="addForm.manager_id" auto-complete="off"></el-input>-->
          <!--
            value-key="id" 此属性就是产生点击效果
            options：此属性就是接收对象，用来展示下拉框数据
            addForm.employee：因为之前绑定的是addFor.manager.id，现在绑定的是对象，所以在新增修改时不会添加数据，
            所以修改后端代码，把新增的sql中传递进去的manager.id换成对象的id
          -->
          <el-select v-model="addForm.employee" placeholder="请选择" value-key="id">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" >
          <!--<el-input v-model="addForm.parent_id" auto-complete="off"></el-input>-->
          <!--addForm.parts 之前绑定的是parent_id,换了之后需要修改sql中传递进去的参数parts.id-->
          <el-cascader v-model="addForm.parts"
              :options="children"
              :props="{
                checkStrictly: true,
                value:'id',/*传递给后台的数据*/
                label:'name'/*展示给用户看的数据*/
              }"
              clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" >
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--新增界面结束-->

    <!--工具条开始-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total, sizes,prev, pager, next"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :page-sizes="[5, 10, 20, 30]"
                     :page-size="pageSize"
                     :total="total" style="float:right;">
      </el-pagination>
    </el-col>
    <!--工具条结束-->

  </section>
</template>


<script>

import {addUser, batchRemoveUser, removeUser} from "../../api/api";
import util from "../../common/js/util";

export default {
  data() {
    return{
      children:[],//做上级部门展示
      departments:[],
      employees:[],
      filters: {//高级查询绑定的事件
        name: ''
      },
      listLoading: true,//有加载的效果，true为开启
      listData:[],//用于列表展示
      sels: [],//列表选中列,多选选中的id数组
      total:0,
      page:1,//默认是第一页
      pageSize:5,//默认展示十条

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      //新增界面需要填写的数据
      addForm: {
        sn:'',
        name: '',
        state: 0,
        manager_id: '',
        parent_id: '',
        employee:{

        },
        parts:{
          id:'',
        }
      },
      title:'',
      //提示用户填写信息
      addFormRules: {
      name: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
      ],
      sn: [
        { required: true, message: '请输入部门编号', trigger: 'blur' }
      ]
    },


    }
  },

  methods:{
    //当点击每页展示条数时
    handleSizeChange(val){
      this.pageSize = val
      this.loadListData()
    },

    //点击触发事件，把当前页数据给page
    handleCurrentChange(val) {
      this.page = val;
      this.loadListData();
    },

    //新增
    addSubmit () {
      //valid是一个布尔类型的值，true弹出模态框
      this.$refs.editForm.validate((valid) => {//校验表单， 通过返回true
        console.debug(valid)
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
              let arr = this.addForm.parts;
            //用户选择的上级部门的数组,判断arr是不是一个数组
              console.debug(arr)
              if (Array.isArray(arr)) {
                console.debug(1111)
                //修改传递到后台的数据
                if (arr.length != 0) {
                  this.addForm.parts = {
                    //传递parent对象，不能解析报错400
                    id: arr[arr.length - 1]
                  }
                }
              }else {
                  console.debug(22222)
                  this.addForm.parts = {
                    //传递parent对象，不能解析报错400
                    id: arr
                  }
                }


            this.$http.put("/department",this.addForm).then(res =>{
              //关闭模态框
              this.addLthoading = false;
              let {success,message} = res.data
              if (success){
                //NProgress.done();
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
              }else {
                this.$message.error('操作失败');
              }
              this.addLoading = false;
              this.addFormVisible=false;
              //刷新数据
              this.loadListData()
            })
          });
        }
      });
    },

    //批量删除
    batchRemove () {
      //使用.toString()此时请求405，格式不匹配
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //发送请求
        this.$http.patch("/department",ids).then(res =>{
          let {success,message} = res.data
          if (success){
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message.error('错了哦，这是一条错误消息');
          }
          //刷新数据
          this.loadListData()
        })
      }).catch(() => {
        this.$message('取消删除成功');
      });
    },

    //普通删除
    handleDel (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        //开启加载数据动画
        this.listLoading = true;
        //发送请求
        this.$http.delete("/department"+"/"+row.id).then(res =>{
        //通过解构的方式拿到后端传递回来的数据
          this.listLoading = false;
          let {success,message} = res.data
          if (success){
            //NProgress.done();
            //刷新数据
            this.loadListData();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message.error('错了哦，这是一条错误消息');
          }

        })

      }).catch(() => {
        this.$message('取消删除成功');
      });
    },

    //打开新增新增模态框
    handleAdd: function () {
      this.title="新增"
      this.addFormVisible = true;
      this.addForm = {
        sn:'',
        name: '',
        state: 0,
        manager_id: '',
        parent_id: '',
        employee:{

        },
        parts:{
          id:'',
        }
      };
    },

    //状态显示转换
    formatSex (row, column) {
      return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
    },

    //修改
    handleEdit (index, row) {
      //回显数据
      this.addForm = Object.assign({}, row);
      console.debug(this.addForm)
      //在新增的时候把parts数组进行了改动为对象，但是回显的时候需要数组,
      //this.addForm.parts=7根据这个测试得到，我们只需要拿到一个上级id就可以了
      this.addForm.parts=row.parent_id
      //弹出模态框
      this.addFormVisible=true
      //给title定义
      this.title="修改"

    },



    selsChange: function (sels) {
      this.sels = sels;
    },

    //发送请求的方法
    loadListData(){
      let param ={
        //把当前页码跟每页要展示的条数传递到后端
        currentPage:this.page,
        pageSize:this.pageSize,
        keywords:this.filters.name //高级查询绑定的事件
      }

      //发送axios请求
      this.$http.post("/department",param).then(res =>{
        console.debug(res)
        this.listData=res.data.data
        this.total=res.data.totals
        this.listLoading=false
      }).catch(res =>{

      })
    },
    //发送请求的方法
    loadListDatagaoji(){
      let param ={
        //把当前页码跟每页要展示的条数传递到后端
        currentPage:1,
        pageSize:this.pageSize,
        keywords:this.filters.name //高级查询绑定的事件
      }

      //发送axios请求
      this.$http.post("/department",param).then(res =>{
        console.debug(res)
        this.listData=res.data.data
        this.total=res.data.totals
        this.listLoading=false
      }).catch(res =>{

      })
    },

    //发送请求获取负责人数据显示到下拉框
    loadEmployee(){
      this.$http.get("/employee").then(res =>{
       console.debug(res)
        //给下拉框的employees赋值
        this.employees=res.data;
      })
    },

    //发送请求拿到部门的多级数据
    loadDeptTree(){
      this.$http.get("/department/loadTree").then(res =>{
        console.debug(res)
        //把查询到的数据给children
        this.children=res.data;
      })
    }

  },

  mounted() {
    //刷新数据
    this.loadListData();
    //获取emp对象数据
    this.loadEmployee();
    this.loadDeptTree();
  }
}

</script>

<style scoped>

</style>